package com.tianxin.workbao.workBao.dataProvide;

import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.tianxin.workbao.workBao.R;
import com.tianxin.workbao.workBao.bean.CoalDao;
import com.tianxin.workbao.workBao.bean.CoalFactory;
import com.tianxin.workbao.workBao.bean.CoalFactoryDao;
import com.tianxin.workbao.workBao.common.Constant;
import com.tianxin.workbao.workBao.common.URL;
import com.tianxin.workbao.workBao.listener.UpdateListViewListener;
import com.tianxin.workbao.workBao.okhttp.CommonOkHttpClient;
import com.tianxin.workbao.workBao.okhttp.exception.OkHttpException;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataHandle;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataListener;
import com.tianxin.workbao.workBao.okhttp.request.CommonRequest;
import com.tianxin.workbao.workBao.okhttp.request.RequestParams;
import com.tianxin.workbao.workBao.utils.common.NetworkUtils;
import com.tianxin.workbao.workBao.utils.common.UIUtils;

import org.greenrobot.greendao.query.Query;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hacker on 2017/7/14.
 */

public class CoalFactoryProvide extends BaseDataProvide {

    private List<CoalFactory> mCoalFactorys;
    private int isFromServer;
    private UpdateListViewListener mUpdateListViewListener;
    private CoalFactoryDao factoryDao;


    public CoalFactoryProvide(Context context, UpdateListViewListener listener) {
        super(context);
        mUpdateListViewListener = listener;
        isFromServer = 0;
        factoryDao = mGreenDaoHelper.getDaoSession().getCoalFactoryDao();
    }

    private void getFromDb() {
        Query<CoalFactory> query = factoryDao.queryBuilder().where(CoalFactoryDao.Properties.Isis.eq(1))
                .build();
        mCoalFactorys = query.list();
    }

    @Override
    public DisposeDataHandle getDisposeDataHandle() {
        disposeDataHandle = new DisposeDataHandle(getDisposeDataListener());
        return disposeDataHandle;
    }

    @Override
    public DisposeDataListener getDisposeDataListener() {
        disposeDataListener = new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                mUpdateListViewListener.hideProgress();
                try {
                    JSONObject object = new JSONObject(responseObj.toString());
                    int status = object.getInt(Constant.RESPONSE_STATUS);
                    String information = object.getString(Constant.RESPONSE_INFO);
                    if (status > 0) {
                        String dataJson = object.getString(Constant.RESPONSE_DATA);
                        if (dataJson != null || dataJson.length() > 2) {
                            try {
                                if (mCoalFactorys != null && !mCoalFactorys.isEmpty()) {
                                    mCoalFactorys.clear();
                                }
                                mCoalFactorys = JSON.parseArray(dataJson, CoalFactory.class);
                                refreshUI();
                                saveToDb(mCoalFactorys);
                            } catch (Exception e) {
                                mUpdateListViewListener.showMessage("coalFactory To Bean Error :类型转换出错" + e.getMessage());
                            }

                        } else {
                            mUpdateListViewListener.showMessage(information);
                        }
                    } else {
                        mUpdateListViewListener.showMessage(information);
                    }

                } catch (JSONException e) {
                    showRequestErrorMessage(mUpdateListViewListener, responseObj.toString());
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Object reasonObj) {
                mUpdateListViewListener.hideProgress();
                if (reasonObj instanceof OkHttpException) {
                    OkHttpException exception = (OkHttpException) reasonObj;
                    mUpdateListViewListener.showMessage(exception.getEcode() + ":" + exception.getEmsg().toString());
                } else {
                    showRequestErrorMessage(mUpdateListViewListener, reasonObj.toString());
                }
            }
        };
        return disposeDataListener;
    }

    /**
     * true save data to databases
     *
     * @param obj
     */
    private void saveToDb(Object obj) {
        if (obj instanceof List) {
            for (int i = 0; i < mCoalFactorys.size(); i++) {
                factoryDao.insertOrReplace(mCoalFactorys.get(i));
            }
        }
    }

    /**
     * get coals 获取列表
     */
    public void getdata() {
        getFromDb();
        if (mCoalFactorys == null || mCoalFactorys.isEmpty()) {
            if (isFromServer == 0) {
                updateFromServer();
            }
        } else {
            refreshUI();
        }

    }

    /**
     * update the coal data  from server
     */
    private void updateFromServer() {
        if (!NetworkUtils.isConnected(UIUtils.getContext())) {
            mUpdateListViewListener.hideProgress();
            mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.poor_network));
        } else {
            mUpdateListViewListener.showProgress();
            isFromServer = 1;
            Map<String, String> map = new HashMap<>();
            map.put(Constant.APPTOKEN_NAME, getAppToken());
            RequestParams params = new RequestParams(map);
            CommonOkHttpClient.post(CommonRequest.createPostRequest(URL.getCoalFactorysUrl(), params), getDisposeDataHandle());
        }
    }

    @Override
    public void refreshUI() {
            mUpdateListViewListener.onRefreshData(mCoalFactorys);
    }
}
